package com.yonyou.brigade.third_parties.didi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.common.exception.CustomException;

/**
 * 滴滴返回结果处理类
 *
 * @author kangfw5
 */
public class DiDiResultUtil {
    private final static String ERR_NO = "errno";
    private final static String ERR_MSG = "errmsg";
    private final static String DATA = "data";

    /**
     * 滴滴返回数据处理
     *
     * @param result 滴滴返回结果
     * @param clazz  接收结果的实体类
     * @return
     */
    public static Object handleResult(String result, Class clazz) {
        JSONObject resultJson;
        try {
            resultJson = JSON.parseObject(result);
        } catch (Exception e) {
            throw new CustomException("调用滴滴企业版服务接口异常");
        }
        if (resultJson.getInteger(ERR_NO) == 0) {
            if (resultJson.get(DATA) instanceof JSONObject) {
                return JSON.parseObject(resultJson.getJSONObject(DATA).toJSONString(), clazz);
            } else if (resultJson.get(DATA) instanceof JSONArray) {
                return JSON.parseArray(resultJson.getJSONArray(DATA).toJSONString(), clazz);
            } else {
                return resultJson.get(DATA);
            }
        } else {
            throw new BusinessException("滴滴服务异常：" + resultJson.getString(ERR_MSG));
        }

    }
}
